'use strict'
const Session = require('../module/session')
const sceneMgr = require('./sceneMgr')
const nodeMgr = require('./nodeMgr')
const route = require('../module/route')
const util = require('util')


//会话管理类(用户连接管理类)
class SessionMgr {
    constructor() {
        this.sessions = {} //保存socket.id对应的session
        this.sessionsPid = {} //保存pId对应的session
        this.curId = 1
    }

    create(socket) {
        let self = this,
            session = new Session(this.curId, socket)
        this.sessions[this.curId] = session
        this.curId += 1
        socket.on('message', function(s, data) {
            self.message(s, data)
        }.bind(this, session))
        session.on('close', function(data) {
            console.debug('用户断开连接')
            let s = data.session
            if (s.pId) {
                //保存用户信息
                let node = nodeMgr.nodes[s.nodeId]
                let sceneId = s.sceneId
                sceneMgr.getSceneSerById(sceneId).dropClient(s.id) //离开当前场景
            }
        })
        return session
    }

    message(session, data) {
        console.log(data)
        let self = this,
            method
        try {
            data = JSON.parse(data)
            if (!util.isObject(data.msg)) {
                data.msg = {}
            }
        } catch (e) {
            return
        }
        if (session.uId) {
            method = route.getLogin(data.route)
            if (method) {
                method(session, data.msg, function(err, result) {
                    self.send(err, result, data.reqId, session)
                })
                return
            }
            let nodeType = route.getNodeType(data.route)
            if (nodeType === 1) {
                nodeMgr.nodes[session.nodeId].send(session.uId, data.route, data.msg, function(err, result) {
                    self.send(err, result, data.reqId, session)
                })
            } else if (nodeType === 2) {
                nodeMgr.chatNode.send(session.uId, data.route, data.msg, function(err, result) {
                    self.send(err, result, data.reqId, session)
                })
            } else if (nodeType === 3) {
                nodeMgr.multiNode.send(session.uId, data.route, data.msg, function(err, result) {
                    self.send(err, result, data.reqId, session)
                })
            }
        } else {
            method = route.getNotLogin(data.route)
            if (method) {
                method(session, data.msg, function(err, result) {
                    self.send(err, result, data.reqId, session)
                })
            } else {
                self.send(data.route + ' 方法不存在', {}, data.reqId, session)
            }
        }
    }

    //发送消息
    send(err, msg, reqId, session) {
        var sendData = {
            msg: msg,
            err: err
        }
        if (reqId) {
            sendData['reqId'] = reqId
        }
        console.log(sendData)
        sendData = JSON.stringify(sendData)
        session.socket.send(sendData)
    }
    getBySid(sId) {
        return this.sessions[sId]
    }
    getByPid(pId) {
        return this.sessionsPid[pId]
    }
    getPIdBySid(sId) {
        return this.sessions[sId].pId
    }
    bind(sId, pId) {
        if (this.sessionsPid[pId]) {
            if (this.sessionsPid[pId].id === sId) {
                //原来的用户重新登陆
                return 0
            }
            //不允许同一账号登陆多个客户端
            //服务器先断开原来的客户端
            //保存用户信息
            let sceneId = this.sessionsPid[pId].sceneId
            sceneMgr.getSceneSerById(sceneId).dropClient(this.sessionsPid[pId].id)
            this.sessionsPid[pId].pId = null
            this.sessionsPid[pId].socket.close()
            this.delSession(this.sessionsPid[pId])
        }
        let session = this.sessions[sId]
        if (!session) {
            return -1
        }
        session.pId = pId
        this.sessionsPid[pId] = session
        return session
    }

    delSession(session) {
        delete this.sessions[session.id]
        delete this.sessionsPid[session.pId]
    }

    delSessionBySid(sId) {
        let session = this.sessions[sId]
        if (session) {
            delete this.sessions[sId]
            if (session.pId) {
                delete this.sessionsPid[session.pId]
            }
        }
    }

    //推送消息到玩家
    pushMsgToPlayer(pId, msg, route) {
        let session = this.sessionsPid[pId]
        if (session) {
            this.pushMsg(msg, route, session)
        }
    }

    //推送消息到当前场景
    pushMsgsToScene(sceneId, msg, route) {
        let clients = sceneMgr.getSceneSerById(sceneId).getClients()
        for (let sId of clients) {
            let session = this.sessions[sId]
            if (session)
                this.pushMsg(msg, route, session)
        }
    }

    //发送消息
    pushMsg(msg, route, session) {
        var sendData = {
            msg: msg,
            route: route
        }
        sendData = JSON.stringify(sendData)
        session.socket.send(sendData)
    }
}
let sessionMgr = new SessionMgr()
module.exports = sessionMgr
